#include "first_chr_dev.h"
#include <linux/types.h>
#include <linux/delay.h>
//#include <linux/kern_levels.h>
#include <linux/uaccess.h>
#define READ_BUF_MAX 2048
#define WRITE_BUF_MAX 2048

static char readbuf[READ_BUF_MAX] = "";
static char kerneldata[] = {"kernel data"};

//打开设备
static int chr_dev_open(struct inode *inode,struct file *filp){

	printk("chr_dev_open");
	return 0;
}

//从设备中读

static ssize_t chr_dev_read(struct file *filp,char __user *buf,size_t cnt,loff_t *offt){

int ret = -1;
int len;
memset(readbuf,0,sizeof(readbuf));

if(READ_BUF_MAX > sizeof(kerneldata)){
	len = sizeof(kerneldata);
}else{
	len = READ_BUF_MAX;
}
memcpy(readbuf,kerneldata,sizeof(kerneldata));
if(cnt>(READ_BUF_MAX - *offt)){
	len = (READ_BUF_MAX - *offt);
}else{
	len = cnt;
}

ret = copy_to_user(buf,readbuf+*offt,len);
if(ret == 0){
	printk("kernel senddata ok!\r\n");
}else{
	printk("kernel sendata filed!\r\n");
}
return len;
}


static ssize_t chr_dev_write(struct file*filp,const char __user *buf,size_t cnt,loff_t *offt){
	return 0;

}


static int chr_dev_release(struct inode*inode,struct file*filp){

	printk("chr_dev_release!\r\n");
	return 0;
}


static struct file_operations chr_dev_fops = {

	.owner = THIS_MODULE,
	.open = chr_dev_open,
	.read = chr_dev_read,
	.write = chr_dev_write,
	.release = chr_dev_release, 

};

static struct first_chr_dev my_first_chr_dev = {
	.dev_name = "first_chr_dev",
	.major = 200,
};

static int chr_dev_init_module(void){

	int ret = -1;
	my_first_chr_dev.fops = chr_dev_fops;
	ret = register_chrdev(my_first_chr_dev.major,my_first_chr_dev.dev_name,&my_first_chr_dev.fops);
	if(ret < 0){
		printk("chr_dev register failed!\r\n");
	}else{
		printk("chr_dev register ok\r\n");
	}
	return 0;

}

static void chr_dev_cleanup_module(void){
	unregister_chrdev(my_first_chr_dev.major,my_first_chr_dev.dev_name);
	printk("cleanup_module\r\n");

}

module_init(chr_dev_init_module);
module_exit(chr_dev_cleanup_module);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("liuzhanchang");
MODULE_DESCRIPTION("first_chr_dev");





